import request from '@/utils/request'
import { mockAPI } from '@/mock/meetingMockAPI'

// 添加JsonData接口定义
export interface JsonData {
  code: number;
  data: any;
  msg: string;
  success: boolean;
}

export enum MeetingType {
  ALL = 'ALL',
  MAIN = 'MAIN',
  PARALLEL = 'PARALLEL',
  SCIENCE = 'SCIENCE',
  PRODUCT = 'PRODUCT',
  ECOLOGY = 'ECOLOGY'
}

export enum MeetingStatus {
  DRAFT = 'DRAFT',               // 草稿
  NOT_STARTED = 'NOT_STARTED',   // 未开始（已发布）
  IN_PROGRESS = 'IN_PROGRESS',   // 进行中
  FINISHED = 'FINISHED',         // 已结束
  CANCELLED = 'CANCELLED'        // 已取消
}

// 会议文件接口
export interface MeetingFile {
  id: string;
  name: string;
  url: string;
  size: number;
  uploadTime: string;
}

// 会议接口
export interface Meeting {
  id: string;
  name: string;
  type: MeetingType;
  status: MeetingStatus;
  begin: string;        // 开始时间
  end: string | null;   // 结束时间
  timeRange?: string;   // 时间范围字段
  location: string;
  description: string;
  coverImage: string;  // 封面图片
  agenda?: string;    // 议程，后端返回JSON字符串
  browseCount: string;      // 浏览次数，后端返回字符串
  goodCount: string;        // 点赞次数，后端返回字符串
  files: MeetingFile[] | null;   // 会议相关文件
  isOnline: boolean;       // 是否线上会议
  videoUrl?: string;       // 视频URL
  maxAttendees?: number | null;    // 最大参会人数
  currentAttendees?: number | null; // 当前参会人数
}

export interface MeetingQuery {
  page: number;
  size: number;
  name?: string;
  type?: MeetingType;
  status?: MeetingStatus;
  dateRange?: string;  // Format: "begin,end"
}

// 议程项类型定义
export interface AgendaItem {
  id: string
  startTime: string
  endTime: string
  title: string
  speaker?: string
  description?: string
}

// 会议文件类型
export interface MeetingFile {
  name: string
  url: string
}

// 添加一个开关来控制是否使用mock数据
// const USE_MOCK = false

// 添加MeetingResponse接口定义
export interface MeetingResponse {
  id: string;
  name: string;
  type: MeetingType;
  status: MeetingStatus;
  begin: string;
  end: string;
  description: string;
  coverImage: string;
  agenda?: string;
  browseCount: string;
  goodCount: string;
  files: MeetingFile[] | null;
  online: boolean;
  maxAttendees?: number | null;
  currentAttendees?: number | null;
}

// 会议表单数据接口
export interface MeetingFormData {
  id?: string;
  name: string;
  type: MeetingType;
  begin: string;
  end: string;
  timeRange?: string;
  location: string;
  description: string;
  coverImage?: string;
  agenda?: string;
  isOnline: boolean | number;  // 允许布尔值或数字
  videoUrl?: string;
  files?: MeetingFile[];
}

export interface MeetingListResponse {
  current_data: Meeting[];
  total_record: number;
}

// 修改getMeetingList函数
export const getMeetingList = async (params: MeetingQuery) => {

  return request.post<any, {
    current_data: Meeting[]
    total_record: number
  }>('/api/meet/list', params)
}

// 修改getMeetingDetail函数
export const getMeetingDetail = async (id: string) => {

  return request.get<any,MeetingResponse>(`/api/meet/meetings/${id}`)
}

/**
 * 上传会议封面
 * @param file 文件对象
 * @param meetId 会议ID
 */
export const uploadMeetingImage = (file: File, meetId: string) => {
  const formData = new FormData()
  formData.append('file', file)
  return request.post<any, {
    code: number,
    data: string,  // 这里的 data 直接是 URL 字符串
    msg: string | null
  }>(`/api/meet/${meetId}/upload_img`, formData)
}

/**
 * 上传会议文件
 * @param file 文件对象
 * @param meetId 会议ID
 */
export const uploadMeetingFile = (file: File, meetId: string) => {
  const formData = new FormData()
  formData.append('file', file)
  return request.post<any, {
    code: number,
    data: string,  // 这里的 data 直接是 URL 字符串
    msg: string | null
  }>(`/api/meet/${meetId}/upload_file`, formData, {
    timeout: 60000, // 增加超时时间到60秒
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 删除会议文件
 * @param meetId 会议ID
 * @param fileUrl 文件URL
 */
export const deleteMeetingFile = (params: { meetId: string, fileUrl: string }) => {
  return request.delete<JsonData>('/api/meet/upload/file', { params })
}

/**
 * 上传会议视频
 * @param file 视频文件
 */
export const uploadMeetingVideo = (file: File, meetId: string) => {
  console.log('uploadMeetingVideo 被调用:', { fileName: file.name, fileSize: file.size, meetId });
  const formData = new FormData()
  formData.append('file', file)
  console.log('准备发送视频上传请求到路径:', `/api/meet/${meetId}/upload_video`);
  return request.post<any, {
    code: number,
    data: string,  // 这里的 data 直接是 URL 字符串
    msg: string | null
  }>(`/api/meet/${meetId}/upload_video`, formData, {
    timeout: 60000, // 增加超时时间到60秒
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  .then(response => {
    console.log('视频上传响应成功:', response);
    return response;
  })
  .catch(error => {
    console.error('视频上传请求失败:', error);
    throw error;
  });
}

/**
 * 删除会议视频
 * @param meetId 会议ID
 * @param videoUrl 视频URL
 */
export const deleteMeetingVideo = (params: { meetId: string, videoUrl: string }) => {
  return request.delete<JsonData>('/api/meet/upload/video', { params })
}

// 修改createMeeting函数
export const createMeeting = async (data: MeetingFormData) => {
  return request.post<JsonData>('/api/meet/meetings', data)
}

// 修改updateMeeting函数
export const updateMeeting = async (id: string, data: Partial<Meeting>) => {
  return request.put<JsonData>(`/api/meet/meetings/${id}`, data)
}

// 修改deleteMeeting函数
export const deleteMeeting = async (id: string) => {

  return request.delete<JsonData>(`/api/meet/meetings/${id}`)
}

// 修改batchDeleteMeetings函数
export const batchDeleteMeetings = async (ids: string[]) => {

  return request.delete<JsonData>('/api/meet/meetings/batch', { data: ids })
}

// 修改updateMeetingStatus函数
export const updateMeetingStatus = async (id: string, status: MeetingStatus) => {
  return request.put<JsonData>(`/api/meet/meetings/${id}/status`, status)
}

// 发布会议
export const publishMeeting = async (id: string) => {

  return request.put<JsonData>(`/api/meet/meetings/${id}/publish`)
}

// 取消会议
export const cancelMeeting = async (id: string) => {
 
  return request.put<JsonData>(`/api/meet/meetings/${id}/cancel`)
}

// 修改 exportMeetingData 函数
export const exportMeetingData = (ids: string[]) => {
  return request.post('/api/meet/export', ids, {
    responseType: 'blob'  // 确保设置了 responseType 为 'blob'
  })
}

// 不需要写后端
// 添加会议状态检查的工具函数
export const checkMeetingStatus = (meeting: Meeting): MeetingStatus | null => {
  const now = new Date().getTime()
  const beginTime = new Date(meeting.begin).getTime()
  const endTime = meeting.end ? new Date(meeting.end).getTime() : beginTime

  // 如果会议已取消，不需要更改状态
  if (meeting.status === MeetingStatus.CANCELLED) {
    return null
  }

  // 如果是草稿状态，不自动更改状态
  if (meeting.status === MeetingStatus.DRAFT) {
    return null
  }

  // 检查是否需要更新状态
  if (meeting.status === MeetingStatus.NOT_STARTED && now >= beginTime) {
    return MeetingStatus.IN_PROGRESS
  } else if (meeting.status === MeetingStatus.IN_PROGRESS && now >= endTime) {
    return MeetingStatus.FINISHED
  }

  return null
}

// 批量更新会议状态
export const batchUpdateMeetingStatus = async (meetings: Meeting[]): Promise<Meeting[]> => {
  const updatePromises = meetings.map(meeting => {
    const newStatus = checkMeetingStatus(meeting)
    if (newStatus) {
      return updateMeetingStatus(meeting.id, newStatus)
        .then(() => ({ ...meeting, status: newStatus }))
    }
    return Promise.resolve(meeting)
  })

  const results = await Promise.all(updatePromises)
  return results
}

// 添加文件信息
export interface AddFileRequest {
  meetId: string;
  fileName: string;
  fileUrl: string;
}

export const addMeetingFile = (data: AddFileRequest) => {
  return request.post<JsonData>('/api/meet/add_file', data)
}

